package ldkxingzhe.ldkxingzhedemo.touchevent;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import ldkxingzhe.ldkxingzhedemo.utils.LogDemo;

/**
 * Created by ke on 15-9-5.
 */
public class VelocityActivity extends AppCompatActivity{

    private final String TAG = VelocityActivity.class.getSimpleName();
    private VelocityTracker velocityTracker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout layout = new LinearLayout(this);
        TextView textView = new TextView(this);
        textView.setText("VelocityActivity");
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout.addView(textView,params);
        setContentView(layout);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int index = event.getActionIndex();
        int action = event.getActionMasked();
        int pointerId = event.getPointerId(index);

        switch (action){
            case MotionEvent.ACTION_DOWN:
                if(velocityTracker == null){
                    velocityTracker = VelocityTracker.obtain();
                }else{
                    velocityTracker.clear();
                }

                velocityTracker.addMovement(event);
                break;
            case MotionEvent.ACTION_MOVE:
                velocityTracker.addMovement(event);
                velocityTracker.computeCurrentVelocity(1000);
                LogDemo.i(TAG, "velocityTracker.getX() = " + velocityTracker.getXVelocity());
                LogDemo.i(TAG,"velocityTracker.getYVelocity() = " + velocityTracker.getYVelocity());
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                LogDemo.v(TAG,"velocityTracker.recycle()");
                velocityTracker.recycle();
                velocityTracker = null;
                break;
        }
        return true;
    }
}
